import 'dart:async';

import 'package:get/get.dart';

class TimerController extends GetxController {
  final int seconds;
  final Function()? callback;

  Timer? _timer;
  int remainingSeconds = 1;
  final time = '00:00:00'.obs;

  TimerController(this.seconds, this.callback);

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    _startTimer();
    super.onReady();
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }

  _startTimer() {
    const duration = Duration(seconds: 1);
    remainingSeconds = seconds;
    _timer = Timer.periodic(duration, (Timer timer) {
      if (remainingSeconds == 0) {
        remainingSeconds = seconds;
        if (callback != null) {
          callback!();
        }
      } else {
        int hours = remainingSeconds ~/ 3600;
        int minutes = remainingSeconds ~/ 60;
        int seconds = (remainingSeconds % 60);
        time.value =
            '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
        remainingSeconds--;
        update();
      }
    });
  }
}
